package com.earthea.application.web.controller.monitor;

import com.earthea.application.common.entity.BaseResult;
import com.earthea.application.common.enums.CacheEnum;
import com.earthea.application.common.utils.StringUtil;
import com.earthea.application.system.domain.entity.SysCache;
import com.earthea.cache.CacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * 缓存监控
 */
@RestController
@RequestMapping("/rest/monitor/cache")
public class CacheController {
    @Autowired
    private CacheService cacheService;

    private final static List<SysCache> caches = Arrays.stream(CacheEnum.values()).map(cacheEnum -> new SysCache(cacheEnum.getPrefix(), cacheEnum.getName())).collect(Collectors.toList());

    @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
    @GetMapping()
    public BaseResult getInfo() throws Exception {
        Map<String, String> info = cacheService.info();
        Map<String, String> commandStats = cacheService.info("commandstats");
        Long dbSize = cacheService.dbSize();

        Map<String, Object> result = new HashMap<>(3);
        result.put("info", info);
        result.put("dbSize", dbSize);

        List<Map<String, String>> pieList = new ArrayList<>();
        commandStats.keySet().forEach(key -> {
            Map<String, String> data = new HashMap<>(2);
            String property = commandStats.get(key);
            data.put("name", StringUtil.removeStart(key, "cmdstat_"));
            data.put("value", StringUtil.substringBetween(property, "calls=", ",usec"));
            pieList.add(data);
        });
        result.put("commandStats", pieList);
        return BaseResult.success(result);
    }

    @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
    @GetMapping("/getNames")
    public BaseResult cache() {
        return BaseResult.success(caches);
    }

    @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
    @GetMapping("/getKeys/{cacheName}")
    public BaseResult getCacheKeys(@PathVariable String cacheName) {
        Set<String> cacheKeys = cacheService.keys(cacheName + "*");
        return BaseResult.success(new TreeSet<>(cacheKeys));
    }

    @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
    @GetMapping("/getValue/{cacheName}/{cacheKey}")
    public BaseResult getCacheValue(@PathVariable String cacheName, @PathVariable String cacheKey) {
        String cacheValue = cacheService.get(cacheKey);
        SysCache sysCache = new SysCache(cacheName, cacheKey, cacheValue);
        return BaseResult.success(sysCache);
    }

    @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
    @DeleteMapping("/clearCacheName/{cacheName}")
    public BaseResult clearCacheName(@PathVariable String cacheName) {
        Collection<String> cacheKeys = cacheService.keys(cacheName + "*");
        cacheKeys.forEach(key -> cacheService.del(key));
        return BaseResult.success();
    }

    @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
    @DeleteMapping("/clearCacheKey/{cacheKey}")
    public BaseResult clearCacheKey(@PathVariable String cacheKey) {
        cacheService.del(cacheKey);
        return BaseResult.success();
    }

    @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
    @DeleteMapping("/clearCacheAll")
    public BaseResult clearCacheAll() {
        Collection<String> cacheKeys = cacheService.keys("*");
        cacheKeys.forEach(key -> cacheService.del(key));
        return BaseResult.success();
    }
}
